package com.tianpengtech.admin.role;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tianpengtech.admin.permission.PermissionDao;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.permission.PermissionDispather;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.string.StringLengthBetween;
import com.tianpengtech.common.validator.rules.string.StringMustBeRequired;

import java.util.List;

public class RoleDispatchImpl implements IRoleDispatch{

    /**数据格式如下
     * {"role":"admin","permissions":["admin:product:add","admin:product:update","admin:product:delete"]}
     * @param v
     */
    public void roleDispatch(String v) throws ValidateException {


        JSONObject object = JSON.parseObject(v);
        String role = object.getString("role");
        String perssmission = buildPermissionStr(object, role);

        Validator validator = new Validator();
        validator.addRule(new StringMustBeRequired(perssmission,"权限信息不能为空"));
        validator.addRule(new StringLengthBetween(perssmission,"权限信息不能超过500个字符",1,500));
        validator.excute();

        PermissionDispather dispather = new PermissionDispather();
        dispather.set(PermissionDispather.ROLE,role);
        dispather.set(PermissionDispather.PERMISSION, perssmission);
        List<PermissionDispather> result = PermissionDao.ME.queryPermissionByRole(role);
        if(result.size()>0){
            dispather.set(PermissionDispather.ID,result.get(0).get(PermissionDispather.ID));
            dispather.update();
        }else{
            dispather.save();
        }

    }


    /*
        批量构建权限操作字符串
     */
    private String buildPermissionStr(JSONObject object, String role) {
        JSONArray permissions = object.getJSONArray("permissions");
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<permissions.size();i++){
            String each = (String)permissions.get(i);
            if(i==permissions.size()-1){
                sb.append(each);
            }else{
                sb.append(each);
                sb.append(",");
            }
        }
        return sb.toString();
    }


}
